import { app, BrowserWindow, ipcMain } from 'electron'
import path from 'node:path'

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.js
// │
process.env.DIST = path.join(__dirname, '../dist')
process.env.PUBLIC = app.isPackaged ? process.env.DIST : path.join(process.env.DIST, '../public')


let win: BrowserWindow | null
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']

function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 830,
    // 窗口是否透明
    transparent: false,
    // 是否展示窗体
    frame: false,
    // 是否可以缩放
    resizable: true,
    // 窗口是否可以最大化
    maximizable: true,
    // 窗口是否可以进入全屏状态
    fullscreenable: true,
    icon: path.join(process.env.PUBLIC, 'electron-vite.svg'),
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false,
      preload: path.join(__dirname, 'preload.js'),
    }
  })

  // debug 启动时打开F12
  // win.webContents.openDevTools()

  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(process.env.DIST, 'index.html'))
  }
}

app.on('window-all-closed', () => {
  win = null
})

// 当electron完成初始化并准备已创建浏览器窗口时，调用creatWindow函数
app.whenReady().then(createWindow)

// 窗口最大化
ipcMain.on('window-max', () => {
  if (!win.isMaximized()) {
    win.maximize()
  } else {
    win.restore()
  }
})

// 窗口最小化
ipcMain.on('window-min', () => {
  win.minimize()
})

// 窗口关闭
ipcMain.on('window-close', () => {
  win.close()
})
